//分页条
function initPage(pageNo,totalCount,arr){
    // 获取分页器实例对象
    var myPager = $('#myPager').data('zui.pager');
    //设置当前页码为 4，并同时设置记录总数为 100， 每页记录数目为 30
    myPager.set(pageNo, totalCount, 5);
    renderConsIntro(arr);
}
$('#myPager').pager({
    onPageChange: function(state, oldState) {
        if (state.page !== oldState.page) {
            // console.log('页码从', oldState.page, '变更为', state.page);
            queryBtn(state.page);
        }
    }
});

//下拉框
var optionList = [];
getFieldList();
function getFieldList(){
    $.ajax({
        url:config.url + "/getFieldList",
        dataType:'json',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        type:'GET' ,
        success:function(resp) {
            addOptionList(resp.data);
        },
        error:function() {
        }
    });
}

function addOptionList(arr){
    for (let i = 0; i < arr.length; i++) {
        optionList.push( {text: arr[i].fieldName + '', value: arr[i].id + '', keys: 'fields'});
    }
    $('#picker6').picker({list: optionList});
}

getUserInfo();
function getUserInfo(){
    $.ajax({
        url:config.url + "/getUserInfo",
        dataType:'json',
        xhrFields: {
            withCredentials: true
        },
        headers:{
            "token":localStorage.getItem("token")
        },
        crossDomain: true,
        type:'GET' ,
        success:function(resp) {
            if(resp.data != null){
                $("#login-reg-btn")[0].innerHTML = "欢迎 " + resp.data;
            }else{
                $("#login-reg-btn")[0].innerHTML = "登录/注册";
            }
        },
        error:function() {
        }
    });
}

//获取咨询师列表
var fieldList = []

function fieldObj(fieldName){
    this.fieldName = fieldName;
}

queryBtn(1);
function queryBtn(i){
    let consName = $('#inputSearchExample3').val();
    fieldList = [];
    let val = $('.picker-selection-text');
    for (let j = 0; j < val.length; j++) {
        fieldList.push(new fieldObj(val[j].innerText));
    }

    $.ajax({
        url:config.url + "/getConsInfo",
        dataType:'json',
        xhrFields: {
            withCredentials: true
        },
        data:{
            consName:consName,
            fieldName:JSON.stringify(fieldList),
            pageNo:i
        },
        crossDomain: true,
        type:'POST',
        success:function(resp) {
            arr = resp.data;
            initPage(arr.pageNo,arr.totalCount,arr);
        },
        error:function() {
        }
    });
}
let arr;
function renderConsIntro(arr){

    let str = '';
    for (let i = 0; i < arr.list.length; i++) {
        let a  = arr.list[i].consultantFieldVos;
        b  = arr.list[i];
        let field = "";
        for (let j = 0; j < a.length; j++) {
            field += a[j].fieldName + "&nbsp;"
        }
        str += `<div class="item flex cons-info-item">
                    <div><img src="img/index/cons${i}.JPG"></div>
                        <div class="intro">
                            <div><span>姓名: </span>${b.name}</div>
                            <div><span>职称: </span>${b.positionalTitles}</div>
                            <div><span>专业: </span>${b.professionalBackground}</div>
                            <div><span>简介: </span>${b.introduction}</div>
                            <div><span>擅长领域: </span>${field}</div>
                                <div class="list">
                                  <header>
                                    <h3><i class="icon-list-ul"></i> 用户评论 <small>更新 ${b.id} 条</small></h3>
                                  </header>
                                <div class="items items-hover">
                                    <div class="item">
                                      <div class="item-heading">
                                        <div class="pull-right"><span class="text-muted">2022-11-11 16:14:37</span> &nbsp; <a href="#" class="text-muted"><i class="icon-comments"></i> 243</a></div>
                                        <h4><a href="###">用户名</a></h4>
                                      </div>
                                      <div class="item-content">
                                        <div class="text">用户评论王老师666</div>
                                      </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="item-btn">
                            <button class="btn btn-success searchBtn btn-lg btn-primary" 
                                    data-toggle="modal" data-target="#myModal"
                                    type="button" onclick="subBtn(${b.id})">点我预约
                            </button>
                        </div>
                </div>`;

        $('#items-wrap')[0].innerHTML = str;
    }
}

var optionList2 = []
var consId;
function subBtn(id){
    consId = id;
    $('#modal-body').val(id);
    var name = '';
    for (let i = 0; i < arr.list.length; i++) {
        let a = arr.list[i].consultantFieldVos;
        b  = arr.list[i];
        if (b.id == id){
            name = b.name;
            for (let j = 0; j < a.length; j++) {
                optionList2.push( {text: a[j].fieldName + '', value: a[j].id + '', keys: 'fields'});
            }
            $('#picker0').picker({list: optionList2});
            break;
        }
    }
    $('#consName').val(name);
    //通过用户id获取日期时间
    getDateTimeInfo(id);
}

function getDateTimeInfo(id){
    $.ajax({
        url:config.url + "/timeInfo",
        dataType:'json',
        xhrFields: {
            withCredentials: true
        },
        data:{
            consId:id
        },
        crossDomain: true,
        type:'GET',
        success:function(resp) {
            var temp = JSON.parse(resp.data);
            renderDate(temp);
        }
    });
}
function renderDate(arr){
    var str1 = `<option value="">请选择</option>`;
    for (let i = 0; i < arr.length; i++) {
        var str = arr[i].dateTime
        let dateAndTime = str.split("-");
        console.log(dateAndTime)
        let year = parseInt(dateAndTime[0]);
        let month = parseInt(dateAndTime[1]);
        let day = parseInt(dateAndTime[2]);
        let hour = parseInt(dateAndTime[3]);
        // list2.push(str);
        let date = year + '-' + month + '-' + day + ' ' + hour +':00';
        //与当前时间 比较
        let myDate = new Date();
        let s1 = myDate.getTime();
        let s2 = new Date(date.replace(/-/g, '/')).getTime();
        let sjc = ( s1 - s2 )/(60*60*1000)
        console.log(sjc);
        if (sjc < 0){
            str1 += `<option value="${date}">${date}</option>`;
        }
    }
    $('#picker3')[0].innerHTML = str1;
}

function submitSubForm(){

    let username = parent.document.getElementById('login-reg-btn').innerText;
    console.log(username);
    username = username.split(' ')[1];
    let fieldName = $('.picker-selection-text')[0].innerText;
    let dataTime = $('#picker3').val();
    let question = $('.question').val();
    if (username == '登录/注册'){
        return alert('请先登录！');
    }
    //ajax获取咨询师费用和用户余额
    $.ajax({
        url:config.url + "/order/haveMoneyForOnlineExam",
        dataType:'json',
        xhrFields: {
            withCredentials: true
        },
        data:{
            username:username, //用户名
        },
        crossDomain: true,
        type:'get',
        success:function(resp) {
            if (resp.code == -1){
                return alert(resp.msg);
            }else{
                //提交表单

                $.ajax({
                    url:config.url + "/order/subscribe",
                    dataType:'json',
                    xhrFields: {
                        withCredentials: true
                    },
                    data:{
                        consId:consId, // 咨询师id
                        username:username, //用户名
                        fieldName:fieldName, //咨询领域
                        dataTime:dataTime, //咨询时间
                        question:question //问题描述
                    },
                    crossDomain: true,
                    type:'POST',
                    success:function(resp) {
                        console.log(resp);
                        alert("提交成功！")
                        location.reload();
                    }
                });
            }
        }
    });

}